package com.changfeng.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.changfeng.auth.annotation.AuthPower;
import com.changfeng.auth.controller.dto.AuthRequest;
import com.changfeng.auth.controller.dto.AuthResponse;
import com.changfeng.auth.dto.UserAuth;
import com.changfeng.auth.util.JwtTokenUtil;
import com.changfeng.bean.RetailersUser;
import com.changfeng.exception.BizExceptionEnum;
import com.changfeng.exception.ChangFengException;
import com.changfeng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class AuthController {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserService userService;

    @PostMapping(value = "#{jwt.path}")
    public AuthResponse createAuthenticationToken(@RequestBody AuthRequest authRequest) {
        System.out.println("user"+authRequest.getUserName());
        RetailersUser user = userService.loginUser(authRequest.getUserName(), authRequest.getPassword());

        if (user != null) {
            UserAuth userAuth = new UserAuth(user.getUserId(),user.getPowerId()!=null?user.getPowerId():0);
            final String randomKey = jwtTokenUtil.getRandomKey();
            final String token = jwtTokenUtil.generateToken(JSONObject.toJSONString(userAuth), randomKey);
            return new AuthResponse(token, randomKey);
        } else {
            throw new ChangFengException(BizExceptionEnum.AUTH_REQUEST_ERROR);
        }
    }

}
